using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using PluginHandler.Database;
using MySql.Data.MySqlClient;

namespace MySqlPlugin.Database
{
    public class DatabaseView : IDatabaseView
    {
        private DatabaseHandler _databaseHandler;
        private string _name;
        private List<IDatabaseTableColumn> _columns;
        private string _queryString;

        internal DatabaseView(DatabaseHandler databaseHandler, string name)
        {
            _databaseHandler = databaseHandler;

            _name = name;
            _columns = null;
            _queryString = null;
        }

        #region IDatabaseView Member

        public List<IDatabaseTableColumn> Columns
        {
            get 
            {
                if (_columns == null)
                {
                    _columns = new List<IDatabaseTableColumn>();

                    DataTable dataTable = GetTableSchema();

                    foreach (System.Data.DataRow dataRow in dataTable.Rows)
                    {
                        string columnName = dataRow["COLUMN_NAME"].ToString();
                        string schemaType = dataRow["DATA_TYPE"].ToString();

                        DbType dataType = DatabaseTableColumn.ConvertStringToDbType(schemaType);

                        _columns.Add(
                            new DatabaseTableColumn(_databaseHandler, this, columnName, dataType, schemaType));
                    }
                }

                return _columns; 
            }
        }

        public string QueryString
        {
            get 
            {
                if (_queryString == null)
                {
                    //TODO: Implement the query string which is behind this view
                    throw new NotImplementedException("Implement the query string which is behind this view.");
                }
                
                return _queryString; 
            }
        }

        #endregion

        #region IDatabaseObject Member

        public string Name
        {
            get { return _name; }
        }

        public string DelimitedIdentifierName
        {
            get
            {
                return _databaseHandler.DelimitedIdentifierBegin + _name + _databaseHandler.DelimitedIdentifierEnd;
            }
        }

        public DataTable GetTableSchema()
        {
            MySqlConnection mySqlConnection = (MySqlConnection)_databaseHandler.DatabaseConnection;
            DataTable schemaInformation = mySqlConnection.GetSchema(
                "Columns",
                new string[] 
                { 
                    null, 
                    _databaseHandler.ConnectionStringDetails["Database"].ToString(), 
                    _name
                });

            return schemaInformation;
        }

        #endregion
    }
}
